/**
 * 中文转换成json脚本
 */
const fs = require('fs');
const path = require('path');
const https = require('https');
const request = require('request');
let allContent = '';
let page = '';
let jsonBody = {};

const containersPath = path.resolve(__dirname,'./src/containers');
const sharePath = path.resolve(__dirname,'./src/share');
const componentsPath = path.resolve(__dirname,'./src/components');
const zh_CN = path.resolve(__dirname,'./src/static/i18n/zh_CN');
const currentEnv= {
  username: '13772118743',
  password: '13772118743',
  artemisAuthorization: 'Basic b3BlcmF0aW9uLXdlYjpLMlF6UFB6M2ZxUU5FbnNid3VwRDFiMUlEUFBnMFJma2RXYWxYeXNMN3dk',
  baseURL: 'https://operation.huilianyi.com'
};

getJson().then(res => {
  jsonBody = res;
  clearIndex();
  directoryChange(containersPath);
  getArtemisToken()
    .then(res=>upMulityLanguageFile(res));
});

/**
 * 清除上一次记录
 */
function clearIndex() {
  let filePath = path.join(zh_CN,'index.json');
  let isExist = fs.existsSync(filePath);
  if(isExist){
    fs.writeFileSync(filePath,'');
  }
}

function directoryChange(filePath){
  let files = fs.readdirSync(filePath);
  files.forEach(fileName => {
    let file = path.join(filePath,fileName);
    let stats = fs.statSync(file);
    allContent = '';
    page = '';
    // 处理每个containers里的文件夹
    if (stats.isDirectory()) {
      getJsContent(file);
      createJson(file);
    }
  });
  // 处理share文件夹
  allContent = '';
  page = '';
  getJsContent(sharePath);
  createJson(sharePath);
  // 处理components文件夹
  allContent = '';
  page = '';
  getJsContent(componentsPath);
  createJson(componentsPath);
  // 外面的文件统一处理
  otherFile(filePath);
}

// 单独放在外面的路径怎么办
function otherFile(filePath) {
  let files = fs.readdirSync(filePath);
  allContent = '';
  page = '';
  let allFile = [];
  files.forEach(fileName => {
    let file = path.join(filePath,fileName);
    let stats = fs.statSync(file);
    if (stats.isFile()) {
      allContent += fs.readFileSync(file, 'utf-8');
      allFile.push(file);
    }
  });
  page = 'dashboard';
  createJson(allFile);
}

/**
 * 项目中中文转换为多语言且生成大json文件
 * @param filePath 需要转成多语言的路径
 */
function getJsContent(filePath){
  let files = fs.readdirSync(filePath);
  files.forEach(fileName => {
    let file = path.join(filePath,fileName);
    let pageIndex = file.split('/');
    page = pageIndex.indexOf('containers') > -1 ? pageIndex[pageIndex.indexOf('containers') + 1] : 'components';
    page === 'supplier-management' && (page = 'supplier');
    page === 'expense-report' && (page = 'expense-parent-report');
    page === 'sub-application' && (page = 'sub-application-view');
    let stats = fs.statSync(file);
    if (stats.isFile()) {
      allContent += fs.readFileSync(file, 'utf-8');
    }
    if (stats.isDirectory()) {
      getJsContent(file);
    }
  });
}

/**
 * 生成二级目录json
 * @param filePath 文件夹名或数组
 */
function createJson(filePath) {
  let contentChinese = [];
  let reg = new RegExp("___([.\n\\s\\S]+?)___","mg");
  let s = reg.exec(allContent);
  while(s){
    if(s[0] && s[0] !== ''){
      contentChinese.push(s[0].replace(/___/g,''));
    }
    s = reg.exec(allContent);
  }
  if(contentChinese.length){
    contentChinese = handleArgs(contentChinese);
    if (contentChinese.length > 0) {
      let zhContent = jsonContent(contentChinese);
      let tempJSON = zhContent.tempRes;
      let allJSON = zhContent.result;
      fs.writeFileSync(path.join(zh_CN,`index2.json`),allJSON);
      fs.writeFileSync(path.join(zh_CN,`index.json`),tempJSON);
    }
    if(typeof filePath === 'string'){
      jsMessages(filePath,false);
    }else{
      filePath.map(item => {
        jsMessages(item,true);
      })
    }
  }
}

/**
 * 中文数组含参数的处理，参数为arg1，arg2，且去重
 * @param arr
 * @returns {*[]}
 */
function handleArgs(arr){
  arr.map((item,index) => {
    item = addArg(item).str;
    arr[index] = item;
  });
  let taskItem = [];
  arr.map((item, index) => {
    isTask(item) && taskItem.push(item) && (item = item.replace(item.split('_')[0] + '_',''));
    arr[index] = item;
  });
  let chinese = [...new Set(arr)]; //arr去重
  chinese.map((item, index) => {
    taskItem.every(it => {
      if(item === it.replace(it.split('_')[0] + '_','')){
        item = it;
        chinese[index] = item;
        return false;
      }
      return true;
    })
  });
  chinese = moveRepeat(chinese,'',false); //在原有的json基础上去重
  chinese = moveRepeat(chinese,zh_CN + '/common.json',true); //去common内去重
  return chinese;
}

function addArg(str) {
  let reg = new RegExp('(\\$)?{([^{}$]+)}','g');
  let args = [];
  let s = reg.exec(str);
  while(s){
    if(s[0] && s[0] !== ''){
      args.push(s[0]);
    }
    s = reg.exec(str);
  }
  args.map((arg,i) => {
    str = str.replace(arg,`{arg${i+1}}`);
  });
  return {
    str, // 存入json
    args // 代码中的参数
  }
}

function isTask(str){
  let task = str ? str.split('_') : [];
  return task.length > 1 && /^[0-9]+$/g.test(task[0])
}

/**
 * 根据指定文件去重
 * @param arr
 * @param filePath
 * @param isCommon
 * @returns {*}
 */
function moveRepeat(arr,filePath,isCommon) {
  let isExist = fs.existsSync(filePath);
  let content = isExist ? fs.readFileSync(filePath,'utf-8') : '';
  filePath === '' && (content = JSON.stringify(jsonBody));
  let regJson = new RegExp("\"([^:^\"]+)\"(\\s)?:(\\s)?\"([^\"]+)\"", "mg");
  content.replace(regJson,(tar,$1,$2,$3,$4) => {
    arr.map((item,index) => {
      isTask(item) && (item = item.replace(item.split('_')[0] + '_',''));
      if(isCommon){
        item === $4 && (arr[index] = undefined);
      }else{
        $1.split('.')[0] === page && item === $4 && (arr[index] = undefined);
      }
    })
  });
  arr = arr.filter(item => !!item);
  return arr;
}

function getResultContent(filePath){
  let tempRes = '';
  let tempContent = fs.readFileSync(filePath).toString();
  (!tempContent || tempContent === '') && (tempContent = '{}');
  let res = JSON.parse(tempContent);
  Object.keys(res).map(item => {
    tempRes += ('\t\t' + `"${item}":${JSON.stringify(res[item])}` + ',\n');
  });
  return tempRes;
}

/**
 * 生成json的内容
 * @param arr 需要新加的中文
 * @returns {{result: (string|string), tempRes: (string|string)}}
 */
function jsonContent(arr) {
  let result = getResultContent(path.join(zh_CN,`index2.json`));
  let tempRes = getResultContent(path.join(zh_CN,`index.json`));
  let i = 0;
  Object.keys(jsonBody).map(item => {
    let numberReg = new RegExp("[a-zA-Z.\\-]","g");
    let number = parseInt(item.replace(numberReg,''));
    item.split('.')[0] === page && (i = (number > i) ? number : i);
  });
  i = Number(i);
  arr.map((item,index) => {
    let items, tempItems;
    if(isTask(item)){
      let itemStr = item.replace(item.split('_')[0] + '_','');
      itemStr = JSON.stringify(itemStr.replace('"','\"'));
      items = '\t\t\"' + page + '.key' + (i+1+index).toString() + '\"\:' + itemStr + (index === arr.length - 1 ? '\n' : ',\n');
      tempItems = '\t\t\"' + page + '.key' + (i+1+index).toString() + '.' + item.split('_')[0] + '\"\:' + itemStr + (index === arr.length - 1 ? '\n' : ',\n');
      jsonBody[`${page}.key${i+1+index}`] = itemStr;
    } else {
      item = JSON.stringify(item.replace('"','\"'));
      items = '\t\t\"' + page + '.key' + (i+1+index).toString() + '\"\:' + item + (index === arr.length - 1 ? '\n' : ',\n');
      tempItems = items;
      jsonBody[`${page}.key${i+1+index}`] = item;
    }
    tempRes += tempItems;
    result += items;
  });
  result = "{\n" + result + "}\n";
  tempRes = "{\n" + tempRes + "}\n";
  return {
    result,
    tempRes
  }
}

function jsMessages(filePath,isFile) {
  let jsonContent = fs.readFileSync(path.join(zh_CN,`index2.json`));
  let commonContent = fs.readFileSync(path.join(zh_CN,`common.json`));
  jsChange(filePath,jsonContent,commonContent,isFile);
}

/**
 * 多语言转换
 * @param filePath 文件夹路径
 * @param jsonContent json内容 json优先级大与common
 * @param commonContent common.json内容
 * @param isFile 单独文件特殊处理
 */
function jsChange(filePath,jsonContent,commonContent,isFile) {
  if(!isFile){
    let files = fs.readdirSync(filePath);
    files.forEach(filename => {
      let fileDir = path.join(filePath,filename);
      let stats = fs.statSync(fileDir);
      if(stats.isFile()){
        reWrite(fileDir,jsonContent,commonContent)
      }
      if(stats.isDirectory()){
        jsChange(fileDir,jsonContent,commonContent,false);
      }
    });
  }else{
    reWrite(filePath,jsonContent,commonContent);
  }
}

function reWrite(fileDir,jsonContent,commonContent) {
  let content = fs.readFileSync(fileDir, 'utf-8');
  // 存在俩个问题 主要由于jsx太强大
  // 1.let a = ['___保存___'] => a = [{messages()}] ❌ a = [messages()] ✅
  // 2.<Modal title='___保存___'/> => title=messages() ❌ title={messages()} ✅
  // 所以每次跑完脚本之后需要启动一下代码
  let jsxReg = new RegExp("([`'\"])?___([.\n\\s\\S]+?)___([`'\"])?","mg");
  content = content.replace(jsxReg,(target,$1,$2) => {
    if(isTask($2)){
      $2 = $2.replace($2.split('_')[0] + '_','');
    }
    let argObj = addArg($2);
    let argArr = [];
    argObj.args.map((item, index) => {
      item = item.replace(/{|}|\$|\s/g,'');
      argArr.push(`arg${index + 1}: ${item}`)
    });
    let indexJson = JSON.parse(jsonContent);
    let commonJson = JSON.parse(commonContent);
    Object.keys(indexJson).map(item => {
      if(item.split('.')[0] === page && JSON.stringify(indexJson[item]) === JSON.stringify(argObj.str)) {
        if($1){
          let note = `messages('${item}'`;
          argArr.length > 0 && (note = `${note},{${argArr.join(',')}}`);
          target = `${note})/*${indexJson[item]}*/`;
        } else {
          let note = `{messages('${item}'`;
          argArr.length > 0 && (note = `${note},{${argArr.join(',')}}`);
          target = `${note})/*${indexJson[item]}*/}`;
        }
      }
    });
    Object.keys(commonJson).map(item => {
      if(JSON.stringify(commonJson[item]) === JSON.stringify(argObj.str)) {
        if($1){
          let note = `messages('${item}'`;
          argArr.length > 0 && (note = `${note},{${argArr.join(',')}}`);
          target = `${note})/*${commonJson[item]}*/`;
        } else {
          let note = `{messages('${item}'`;
          argArr.length > 0 && (note = `${note},{${argArr.join(',')}}`);
          target = `${note})/*${commonJson[item]}*/}`;
        }
      }
    });
    return target;
  });
  /************************增加messages的引入**************************/
  let needAdd = true;
  let reg1 = new RegExp("import(\\s*){([a-zA-Z,\\s]+)}(\\s*)from(\\s*)(['\"])share/common(['\"])(\\s*)(;)?","g");
  let has = content.match(reg1);
  content = content.replace(reg1,(target,$1,$2) => {
    let temp = $2.match('messages');
    if(temp){
      needAdd = false;
    }
    return target;
  });
  let regs = new RegExp('messages\\((["\'])([^"\']+?)(["\'])(/\\*([.\\s\\S]+?)\\*/)?\\)(/\\*([.\\s\\S]+?)\\*/)?','mg');
  let need = content.match(regs);
  if(needAdd && need){
    if(has){
      content = content.replace(reg1,(target,$1,$2) => {
        $2 = `${$2}, messages `;
        target = `import {${$2}} from "share/common";\n`;
        return target;
      });
    }else{
      content = 'import {messages} from \"share/common\";\n' + content;
    }
  }
  fs.writeFileSync(fileDir, content);
}

function getJson() {
  return new Promise((resolve, reject) => {
    request.get({
      url: 'https://cloudhelios-static.oss-cn-shanghai.aliyuncs.com/multilanguage/web_prod_zh_cn.json'
    },(err, httpResponse, body) => {
      if (err) {
        console.log('远程json获取失败')
      } else {
        if (body) {
          let temp = JSON.parse(body);
          resolve(temp)
        } else {
          reject('');
        }
      }
    })
  })
}

// 获取运营平台token
function getArtemisToken() {
  return new Promise((resolve, reject) => {
    let formData = {
      "scope": 'write',
      "grant_type": "password",
      "username": currentEnv.username,
      "password": currentEnv.password,
    };
    request.post(
      {
        url:  currentEnv.baseURL + '/oauth/token',
        formData: formData,
        headers: {
          'Authorization': currentEnv.artemisAuthorization
        }
      },
      function optionalCallback(err, httpResponse, body) {
        if (err) {
          console.error('获取' + formData.username + ' 认证失败 ', err);
          reject(err);
        }
        else {
          if (body) {
            console.log('获取' + formData.username + ' 认证成功！');
            let parsedBody= JSON.parse(body);
            console.log('Token ' + parsedBody.access_token);
            resolve(parsedBody)
          } else {
            reject('error');
          }
        }

      });
  });
}
// 上传多语言文件
function upMulityLanguageFile(res){
  if(res && res.access_token){
    let token= res.access_token;
    let fileContent= fs.readFileSync(path.join(zh_CN,'index.json'));
    fileContent = fileContent.toString();
    console.log('fileContent', fileContent);
    const options = {
      hostname: 'operation.huilianyi.com',
      port: 443,
      path: `/api/multilanguage/analysis?client=web&language=zh_cn`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    };
    let req= https.request(options, res=>{
      console.log('准备上传');
      let chunkStr= '';
      res.setEncoding('utf8');
      res.on('data', (chunk) => {
        chunkStr+= chunk;
        console.log(`响应主体: ${chunk}`);
      });
      res.on('end',()=>{
        console.log('上传成功');
      })
    });
    req.write(fileContent);
    req.end();
  }
}
